package com.wlgzs.booksystem.controller.back;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.wlgzs.booksystem.entity.Book;
import com.wlgzs.booksystem.entity.Ext.BookExt;
import com.wlgzs.booksystem.entity.Category;
import com.wlgzs.booksystem.entity.Ext.Books;
import com.wlgzs.booksystem.enums.Result;
import com.wlgzs.booksystem.enums.ResultCodeEnum;
import com.wlgzs.booksystem.service.BookService;
import com.wlgzs.booksystem.service.CategoryService;
import com.wlgzs.booksystem.service.FileService;
import com.wlgzs.booksystem.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wlgzs-sjl
 * @since 2020-11-17
 */
@RestController
@RequestMapping("/back/book")
@Api(tags = "图书管理")
public class BookController {
    @Autowired
    BookService bookService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    FileService fileService;

    @Value("${qiniu.path}")
    private String path;

    @GetMapping
    @ApiOperation(value = "后台图书管理主页",httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页(默认为1)", defaultValue = "1",required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每一页的大小(默认为10)", defaultValue = "10",required = true, dataType = "int")
    })
    public Result bookIndex(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size){
        Page<Book> page=new Page<>(current,size);
        List<Book> bookList=bookService.page(page,null).getRecords();
        List<Books> books=new ArrayList<>();
        for (Book b:bookList){
            Books books1=new Books();
            books1.setCategoryName(categoryService.getById(b.getCategoryId()).getCategoryName());
            books1.setBook(b);
            books.add(books1);
        }
        List<Category> categories=categoryService.list();
        BookExt bookExt=new BookExt(books,categories,(page.getTotal()+size)/size);
        return new Result(ResultCodeEnum.SUCCESS,bookExt);
    }

    @GetMapping("/updateIndex")
    @ApiOperation(value = "后台修改图书页面",httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bookId", value = "书本id", required = true, dataType = "int")
    })
    public Result updateIndex(Integer bookId){
        Book book=bookService.getById(bookId);
        Books books=new Books();
        books.setBook(book);
        books.setCategoryName(categoryService.getById(book.getCategoryId()).getCategoryName());
        List<Category> categories=categoryService.list();
        BookExt bookExt=new BookExt((List<Books>) books,categories,0L);
        return new Result(ResultCodeEnum.SUCCESS,bookExt);
    }

    @GetMapping("/findByName")
    @RequiresRoles(value = "user")
    @ApiOperation(value = "根据书名查找书",httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页(默认为1)", defaultValue = "1",required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每一页的大小(默认为10)", defaultValue = "10",required = true, dataType = "int"),
            @ApiImplicitParam(name = "name", value = "书名", required = true, dataType = "String")
    })
    public Result findBooksByName(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size,String name){
        Page<Book> page=new Page<>(current,size);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("book_name",name);
        List<Book> books=bookService.page(page,wrapper).getRecords();
        List<Books> bookList=new ArrayList<>();
        for (Book b:books){
            Books books1=new Books();
            books1.setCategoryName(categoryService.getById(b.getCategoryId()).getCategoryName());
            books1.setBook(b);
            bookList.add(books1);
        }
        BookExt bookExt=new BookExt(bookList,null,(page.getTotal()+size)/size);
        if (books!=null){
            return new Result(ResultCodeEnum.FIND,bookExt);
        }else {
            return new Result(ResultCodeEnum.UNFIND);
        }
    }

    @GetMapping("/findByCategory")
    @RequiresRoles(value = {"role","user"})
    @ApiOperation(value = "根据类别查找书",httpMethod = "GET", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页(默认为1)", defaultValue = "1",required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每一页的大小(默认为10)", defaultValue = "5",required = true, dataType = "int"),
            @ApiImplicitParam(name = "categoryId", value = "类别id", required = true, dataType = "int")
    })
    public Result findBooksByCategory(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size,int categoryId){
        Page<Book> page=new Page<>(current,size);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("category_id",categoryId);
        List<Book> books=bookService.page(page,wrapper).getRecords();
        List<Books> bookList=new ArrayList<>();
        for (Book b:books){
            Books books1=new Books();
            books1.setCategoryName(categoryService.getById(b.getCategoryId()).getCategoryName());
            books1.setBook(b);
            bookList.add(books1);
        }
        BookExt bookExt=new BookExt(bookList,null,(page.getTotal()+size)/size);
        return new Result(ResultCodeEnum.SUCCESS,bookExt);
    }

    @DeleteMapping
    @ApiOperation(value = "删除书",httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bookId", value = "书本id", required = true, dataType = "int")
    })
    public Result deleteBookById(int bookId){
        if (bookService.removeById(bookId)){
            return new Result(ResultCodeEnum.DELETE);
        }else {
            return new Result(ResultCodeEnum.UNDELETE);
        }
    }

    @DeleteMapping("/many")
    @ApiOperation(value = "批量删除书",httpMethod = "DELETE", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bookIds", value = "书本id的集合", required = true, dataType = "String")
    })
    public Result deleteManyBookByIds(String bookIds){
        String[] list=bookIds.split(",");
        for(String s:list){
            bookService.removeById(Integer.parseInt(s));
        }
        return new Result(ResultCodeEnum.DELETE);
    }

    @PostMapping
    @ApiOperation(value = "添加或修改书",httpMethod = "POST", response = Result.class)
    public Result insertBook(Book book , MultipartFile upfile){
        if (upfile!=null){
            try{
                String imageName = fileService.uploadFile(upfile);
                book.setPicture(path+"/"+imageName);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        if (bookService.saveOrUpdate(book)){
            return new Result(ResultCodeEnum.SUCCESS);
        }else {
            return new Result(ResultCodeEnum.FAIL);
        }
    }
}

